<template>
  <div class="transaction-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>交易管理</span>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="90px">
        <el-form-item label="车辆ID" prop="carId">
          <el-input v-model.number="queryParams.carId" placeholder="请输入车辆ID" clearable />
        </el-form-item>
        <el-form-item label="买家ID" prop="buyerId">
          <el-input v-model.number="queryParams.buyerId" placeholder="请输入买家ID" clearable />
        </el-form-item>
        <el-form-item label="经销商ID" prop="dealerId">
          <el-input v-model.number="queryParams.dealerId" placeholder="请输入经销商ID" clearable />
        </el-form-item>
        <el-form-item label="交易状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择交易状态" clearable>
            <el-option 
              v-for="item in transactionStatusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支付状态" prop="paymentStatus">
          <el-select v-model="queryParams.paymentStatus" placeholder="请选择支付状态" clearable>
            <el-option 
              v-for="item in paymentStatusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="queryParams.paymentMethod" placeholder="请选择支付方式" clearable>
            <el-option 
              v-for="item in paymentMethodOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区域 -->
      <el-row :gutter="10" class="mb-2">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon> 新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon> 批量删除
          </el-button>
        </el-col>
      </el-row>

      <!-- 交易列表 -->
      <el-table
        v-loading="loading"
        :data="transactionList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="交易ID" width="100" align="center" />
        <el-table-column label="车辆信息" width="200">
          <template #default="scope">
            <div v-if="scope.row.car">
              <div>ID: {{ scope.row.carId }}</div>
              <div>车牌: {{ scope.row.car.carNumber }}</div>
              <div>品牌: {{ scope.row.car.carBrand }}</div>
            </div>
            <div v-else>车辆ID: {{ scope.row.carId }}</div>
          </template>
        </el-table-column>
        <el-table-column label="买家信息" width="180">
          <template #default="scope">
            <div v-if="scope.row.buyer">
              <div>ID: {{ scope.row.buyerId }}</div>
              <div>用户名: {{ scope.row.buyer.username }}</div>
              <div>昵称: {{ scope.row.buyer.nickname }}</div>
            </div>
            <div v-else>买家ID: {{ scope.row.buyerId }}</div>
          </template>
        </el-table-column>
        <el-table-column label="经销商信息" width="180">
          <template #default="scope">
            <div v-if="scope.row.dealer">
              <div>ID: {{ scope.row.dealerId }}</div>
              <div>名称: {{ scope.row.dealer.dealerName }}</div>
              <div>联系人: {{ scope.row.dealer.contactPerson }}</div>
            </div>
            <div v-else>经销商ID: {{ scope.row.dealerId }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="成交价格" width="150" align="right">
          <template #default="scope">
            {{ formatPrice(scope.row.price) }}
          </template>
        </el-table-column>
        <el-table-column label="交易日期" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.transactionDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120" />
        <el-table-column label="支付状态" width="120">
          <template #default="scope">
            <el-tag :type="getPaymentStatusType(scope.row.paymentStatus)">
              {{ formatPaymentStatus(scope.row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="交易状态" width="120">
          <template #default="scope">
            <el-tag :type="getTransactionStatusType(scope.row.status)">
              {{ formatTransactionStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="合同" width="100">
          <template #default="scope">
            <el-button v-if="scope.row.contractUrl" link type="primary" @click="viewContract(scope.row)">
              查看合同
            </el-button>
            <span v-else>暂无合同</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.status === 0" link type="success" @click="handleComplete(scope.row)">完成</el-button>
            <el-button v-if="scope.row.status === 0" link type="warning" @click="handleCancel(scope.row)">取消</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 添加/编辑交易对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="650px"
      append-to-body
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="车辆ID" prop="carId">
          <el-input v-model.number="form.carId" placeholder="请输入车辆ID" />
        </el-form-item>
        <el-form-item label="买家ID" prop="buyerId">
          <el-input v-model.number="form.buyerId" placeholder="请输入买家ID" />
        </el-form-item>
        <el-form-item label="经销商ID" prop="dealerId">
          <el-input v-model.number="form.dealerId" placeholder="请输入经销商ID" />
        </el-form-item>
        <el-form-item label="交易日期" prop="transactionDate">
          <el-date-picker
            v-model="form.transactionDate"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 0, 1, 12, 0, 0)"
          />
        </el-form-item>
        <el-form-item label="成交价格" prop="price">
          <el-input v-model.number="form.price" placeholder="请输入成交价格">
            <template #prefix>￥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="form.paymentMethod" placeholder="请选择支付方式">
            <el-option 
              v-for="item in paymentMethodOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支付状态" prop="paymentStatus">
          <el-select v-model="form.paymentStatus" placeholder="请选择支付状态">
            <el-option 
              v-for="item in paymentStatusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合同URL" prop="contractUrl">
          <el-input v-model="form.contractUrl" placeholder="请输入合同文件URL" />
        </el-form-item>
        <el-form-item label="交易状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择交易状态">
            <el-option 
              v-for="item in transactionStatusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看交易详情对话框 -->
    <el-dialog
      title="交易详情"
      v-model="viewDialogVisible"
      width="700px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="交易ID">{{ viewForm.id }}</el-descriptions-item>
        <el-descriptions-item label="交易日期">{{ formatDate(viewForm.transactionDate) }}</el-descriptions-item>
        <el-descriptions-item label="车辆ID">{{ viewForm.carId }}</el-descriptions-item>
        <el-descriptions-item label="买家ID">{{ viewForm.buyerId }}</el-descriptions-item>
        <el-descriptions-item label="经销商ID">{{ viewForm.dealerId }}</el-descriptions-item>
        <el-descriptions-item label="成交价格">{{ formatPrice(viewForm.price) }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ viewForm.paymentMethod }}</el-descriptions-item>
        <el-descriptions-item label="支付状态">
          <el-tag :type="getPaymentStatusType(viewForm.paymentStatus)">
            {{ formatPaymentStatus(viewForm.paymentStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="交易状态">
          <el-tag :type="getTransactionStatusType(viewForm.status)">
            {{ formatTransactionStatus(viewForm.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(viewForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(viewForm.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="合同文件" :span="2">
          <el-link v-if="viewForm.contractUrl" type="primary" :href="viewForm.contractUrl" target="_blank">
            {{ viewForm.contractUrl }}
          </el-link>
          <span v-else>暂无合同</span>
        </el-descriptions-item>
      </el-descriptions>

      <template v-if="viewForm.car">
        <h3 class="detail-title">车辆信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="车牌号">{{ viewForm.car.carNumber }}</el-descriptions-item>
          <el-descriptions-item label="品牌">{{ viewForm.car.carBrand }}</el-descriptions-item>
          <el-descriptions-item label="指导价">{{ formatPrice(viewForm.car.guidePrice) }}</el-descriptions-item>
        </el-descriptions>
      </template>

      <template v-if="viewForm.buyer">
        <h3 class="detail-title">买家信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户名">{{ viewForm.buyer.username }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{ viewForm.buyer.nickname }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{ viewForm.buyer.phone }}</el-descriptions-item>
        </el-descriptions>
      </template>

      <template v-if="viewForm.dealer">
        <h3 class="detail-title">经销商信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="经销商名称">{{ viewForm.dealer.dealerName }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ viewForm.dealer.contactPerson }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ viewForm.dealer.contactPhone }}</el-descriptions-item>
        </el-descriptions>
      </template>
    </el-dialog>

    <!-- 查看合同对话框 -->
    <el-dialog
      title="合同文件"
      v-model="contractDialogVisible"
      width="800px"
      append-to-body
    >
      <iframe 
        v-if="selectedContract" 
        :src="selectedContract" 
        width="100%" 
        height="500px"
        frameborder="0"
      ></iframe>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getTransactionsByPage,
  getTransactionById,
  addTransaction,
  updateTransaction,
  deleteTransaction,
  batchDeleteTransactions,
  updateTransactionStatus,
  updatePaymentStatus,
  getPaymentMethodOptions,
  getPaymentStatusOptions,
  getTransactionStatusOptions,
  formatPaymentStatus as formatPaymentStatusUtil,
  formatTransactionStatus as formatTransactionStatusUtil
} from '@/api/transaction'
import { Search, Refresh, Plus, Delete } from '@element-plus/icons-vue'

// 数据加载状态
const loading = ref(false)
// 交易列表数据
const transactionList = ref([])
// 总记录数
const total = ref(0)
// 选中的交易ID列表
const selectedIds = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  carId: undefined,
  buyerId: undefined,
  dealerId: undefined,
  status: undefined,
  paymentStatus: undefined,
  paymentMethod: undefined
})

// 表单参数
const form = ref({
  id: undefined,
  carId: undefined,
  buyerId: undefined,
  dealerId: undefined,
  transactionDate: undefined,
  price: undefined,
  paymentMethod: undefined,
  paymentStatus: undefined,
  contractUrl: undefined,
  status: 0
})

// 查看表单参数
const viewForm = ref({})

// 对话框显示状态
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const contractDialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const selectedContract = ref('')

// 表单校验规则
const rules = {
  carId: [
    { required: true, message: '请输入车辆ID', trigger: 'blur' },
    { type: 'number', message: '车辆ID必须为数字', trigger: 'blur' }
  ],
  buyerId: [
    { required: true, message: '请输入买家ID', trigger: 'blur' },
    { type: 'number', message: '买家ID必须为数字', trigger: 'blur' }
  ],
  dealerId: [
    { required: true, message: '请输入经销商ID', trigger: 'blur' },
    { type: 'number', message: '经销商ID必须为数字', trigger: 'blur' }
  ],
  transactionDate: [
    { required: true, message: '请选择交易日期', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入成交价格', trigger: 'blur' },
    { type: 'number', message: '成交价格必须为数字', trigger: 'blur' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  paymentStatus: [
    { required: true, message: '请选择支付状态', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择交易状态', trigger: 'change' }
  ]
}

// 选项数据
const paymentMethodOptions = getPaymentMethodOptions()
const paymentStatusOptions = getPaymentStatusOptions()
const transactionStatusOptions = getTransactionStatusOptions()

// 获取交易列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getTransactionsByPage(
      queryParams.pageNum,
      queryParams.pageSize,
      {
        carId: queryParams.carId,
        buyerId: queryParams.buyerId,
        dealerId: queryParams.dealerId,
        status: queryParams.status,
        paymentStatus: queryParams.paymentStatus,
        paymentMethod: queryParams.paymentMethod
      }
    )
    transactionList.value = res.data || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取交易列表失败:', error)
    ElMessage.error('获取交易列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.carId = undefined
  queryParams.buyerId = undefined
  queryParams.dealerId = undefined
  queryParams.status = undefined
  queryParams.paymentStatus = undefined
  queryParams.paymentMethod = undefined
  handleQuery()
}

// 表格多选框选中数据
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页页码改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 分页条数改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  isEdit.value = false
  dialogTitle.value = '添加交易'
  dialogVisible.value = true
  form.value.transactionDate = new Date().toISOString().slice(0, 19).replace('T', ' ')
  form.value.status = 0
  form.value.paymentStatus = 0
}

// 编辑按钮操作
const handleEdit = (row) => {
  reset()
  isEdit.value = true
  dialogTitle.value = '编辑交易'
  const transaction = JSON.parse(JSON.stringify(row))
  form.value = transaction
  dialogVisible.value = true
}

// 查看详情按钮操作
const handleView = async (row) => {
  try {
    const res = await getTransactionById(row.id)
    viewForm.value = res
    viewDialogVisible.value = true
  } catch (error) {
    console.error('获取交易详情失败:', error)
    ElMessage.error('获取交易详情失败')
  }
}

// 查看合同操作
const viewContract = (row) => {
  if (row.contractUrl) {
    selectedContract.value = row.contractUrl
    contractDialogVisible.value = true
  } else {
    ElMessage.warning('该交易暂无合同文件')
  }
}

// 完成交易操作
const handleComplete = (row) => {
  ElMessageBox.confirm('确认将该交易标记为已完成吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateTransactionStatus(row.id, 1)
      ElMessage.success('操作成功')
      getList()
    } catch (error) {
      console.error('更新交易状态失败:', error)
      ElMessage.error('更新交易状态失败')
    }
  }).catch(() => {})
}

// 取消交易操作
const handleCancel = (row) => {
  ElMessageBox.confirm('确认将该交易标记为已取消吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateTransactionStatus(row.id, 2)
      ElMessage.success('操作成功')
      getList()
    } catch (error) {
      console.error('更新交易状态失败:', error)
      ElMessage.error('更新交易状态失败')
    }
  }).catch(() => {})
}

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该交易记录吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteTransaction(row.id)
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除交易失败:', error)
      ElMessage.error('删除交易失败')
    }
  }).catch(() => {})
}

// 批量删除操作
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条交易记录吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await batchDeleteTransactions(selectedIds.value.join(','))
      getList()
      ElMessage.success('批量删除成功')
    } catch (error) {
      console.error('批量删除交易失败:', error)
      ElMessage.error('批量删除交易失败')
    }
  }).catch(() => {})
}

// 表单重置
const reset = () => {
  form.value = {
    id: undefined,
    carId: undefined,
    buyerId: undefined,
    dealerId: undefined,
    transactionDate: undefined,
    price: undefined,
    paymentMethod: undefined,
    paymentStatus: undefined,
    contractUrl: undefined,
    status: 0
  }
}

// 表单提交
const submitForm = async () => {
  try {
    if (isEdit.value) {
      await updateTransaction(form.value)
      ElMessage.success('修改成功')
    } else {
      await addTransaction(form.value)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('提交交易失败:', error)
    ElMessage.error('提交交易失败')
  }
}

// 格式化支付状态
const formatPaymentStatus = (status) => {
  return formatPaymentStatusUtil(status)
}

// 格式化交易状态
const formatTransactionStatus = (status) => {
  return formatTransactionStatusUtil(status)
}

// 获取支付状态对应的标签类型
const getPaymentStatusType = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'success',
    2: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取交易状态对应的标签类型
const getTransactionStatusType = (status) => {
  const statusMap = {
    0: 'primary',
    1: 'success',
    2: 'danger'
  }
  return statusMap[status] || 'info'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 格式化价格
const formatPrice = (price) => {
  if (price === undefined || price === null) return '¥0.00'
  return `¥${Number(price).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}

// 页面加载时获取交易列表
onMounted(() => {
  getList()
})
</script>

<style scoped>
.transaction-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 20px;
}

.mb-2 {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.detail-title {
  margin-top: 20px;
  margin-bottom: 10px;
  font-weight: bold;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}
</style> 